﻿"""Appengine datastore models"""

from google.appengine.ext import db
from qproc import QueryProcessor

class RequestLog(db.Model):
    """Model representing every request to the 'results' page"""
    stop = db.StringProperty()
    line = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    remote_addr = db.StringProperty()
    url = db.StringProperty()
    headers = db.TextProperty()

class StopModel(db.Model):
    """Model representing every stop"""
    number = db.IntegerProperty()
    name = db.StringProperty()
    description = db.StringProperty()
    services = db.StringListProperty()
    
class Stop(object):
    """Wrapper of StopModel"""
    def __init__(self, stop_number, query_processor, update_datastore=False):
        """Load (if exists) or create corresponding StopModel entity"""
        self.id = str(stop_number).zfill(4)
        self.query_processor = query_processor
        d = query_processor.get_stop_info(stop_number)
        self.stop_entity = StopModel.get_or_insert('Stop' + self.id, number=stop_number,
            name=d['name'], description=d['description'], services=d['services'])
        self.stop_entity.number = stop_number
        self.stop_entity.name = d['name']
        self.stop_entity.description = d['description']
        self.stop_entity.services = d['services']            
        if update_datastore:
            self.update()
        
    def update(self):
        """Update the datastore with the acquired info in __init__"""
        self.stop_entity.put()
    
    def __getattr__(self, name):
        """Get attributes from corresponding StopModel entity"""
        return self.stop_entity.__getattribute__(name)
    
    def vehicles(self, service):
        """Return scheduled times for vehicles of the given service"""
        return self.query_processor.get_vehicles(self.stop_entity.number, service)

class Bookmark(db.Model):
    """Model representing every saved page (item of user's list)"""
    user = db.UserProperty()
    nickname = db.StringProperty()
    id = db.IntegerProperty()
    name = db.StringProperty()
    stop_numbers = db.ListProperty(int)
    service_patterns = db.StringListProperty()
    time_limit = db.IntegerProperty()
    
    def __getattribute__(self, name):
        """Process special attributes"""
        if name == 'pretty_stop_numbers':
            return ','.join(map(str, self.stop_numbers))
        elif name == 'pretty_service_patterns':
            return ','.join(self.service_patterns)
        elif name == 'pretty_time_limit':
            return str(self.time_limit) if self.time_limit else ''
        else:
            return object.__getattribute__(self, name)